#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# :CREATED: [2018-04-26 Thu 21:36]
# :AUTHOR: zb
from sqlalchemy import Column, Integer, String, DateTime
from models.base import Models, Base
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo


class Server(Models, Base):
    __tablename__ = 'server'

    id = Column(Integer, primary_key=True)
    ip = Column(String)
    username = Column(String)
    password = Column(String)
    domain = Column(String)
    servername = Column(String)


class ServerForm(FlaskForm):

    ip = StringField('ip', validators=[DataRequired(), Length(1, 64)])
    username = StringField(
        'username', validators=[DataRequired(), Length(1, 64)])
    password = StringField(
        'password', validators=[DataRequired(), Length(1, 64)])
    domain = StringField('domain', validators=[Length(1, 64)])
    servername = StringField('servername', validators=[Length(1, 64)])
    submit = SubmitField('Add Server')


class ServerTime(Models, Base):
    __tablename__ = 'server_time'

    id = Column(Integer, primary_key=True)
    server_id = Column(String)
    server_time = Column(String)
    update_time = Column(DateTime)


class ServerTimeForm(FlaskForm):

    ip = StringField('ip', validators=[DataRequired(), Length(1, 64)])
    domain = StringField('domain', validators=[DataRequired(), Length(1, 10)])
    servername = StringField(
        'servername', validators=[DataRequired(),
                                  Length(1, 64)])
    time = StringField('time', validators=[DataRequired(), Length(1, 64)])


class ServerQueryForm(FlaskForm):
    
    domain = StringField('domain', validators=[Length(0, 10)])


class Url_address(Models, Base):
    __tablename__ = 'url_address'
    id = Column(Integer, primary_key=True)
    app_code = Column(String)
    domain = Column(String)
    IP = Column(String)
    port = Column(String)
    NAT_port = Column(String)
    NAT_IP = Column(String)
    login_name = Column(String)
    login_password = Column(String)

    def set_intranet_url(self, url):
        self.intranet_url = url 

    def set_external_url(self, url):
        self.external_url = url


class app_path_map(Models, Base):
    __tablename__ = 'app_path_map'
    id = Column(Integer, primary_key=True)
    app_code = Column(String)
    app_name = Column(String)
    path_prefix = Column(String)
    path_suffix = Column(Integer)


def read_from_csv(path, coding='utf-8'):
    import csv
    with open(path, newline='', encoding=coding) as csvfile:
        reader = csv.DictReader(csvfile)
        return list(reader)


def save_(table, datas):
    s_l = [table.new(**s) for s in datas]
    table.insert_all(s_l).commit()


def init_table(table, path, coding='utf-8'):

    datas = read_from_csv(path,coding=coding)
    save_(table, datas)
